import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gridItems: [
      {id: 1,value: 1},
      {id: 2,value: 2},
      {id: 3,value: 3},
      {id: 0,value: 0},
      {id: 4,value: 4},
      {id: 5,value: 5},
      {id: 6,value: 6},
      {id: 'minus',value: '-'},
      {id: 7,value: 7},
      {id: 8,value: 8},
      {id: 9,value: 9},
      {id: 'delete',value: '删除'}
    ],//键盘
    value: '',//点击键盘的值
    tabNum: -1,//键盘高亮默认值
    scaleValue: [], //左边刻度值
    childHeight: 0,//左边刻度的高度
    leftValue: 0, //左边刻度答案
    randomIndex:0,//左边刻度答案的索引值
    middleArray:[],//右边刻度值
    rightValue:0,//右边刻度答案
    firstNumber:0,//右边刻度第一个数
    lastNumber:0,//右边刻度最后一个数
    charList:[],//圆形刻度的数据
    zoneScale:0,//圆形刻度0的角度
    answerValue:0,//圆形刻度答案
    isCircleTopic:false,//是否是圆形刻度题目
    isLeftTopic:false,//是否是左边刻度题目
    isRightTopic:false,//是否是右边刻度题目
    totalCount: 0, //题目总数
    questionIndex: 0, //当前题型索引
    count: 0, //记录做题次数
    countdownTime: 60, // 倒计时时间
    countdownInterval: null, // 存储 interval ID
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
    isExercise: true, //是否是练习题
    ratioResult:app.globalData.ratioResult
  },
  onLoad() {
    this.getHeight();
    this.leftScaleValue();
    this.rightScaleValue();
    this.getTopicData();
    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
    console.log(this.data.ratioResult)
  },
  // 获取题目信息
  getTopicData() {
    const questionInfo = wx.getStorageSync('questionInfo');
    const questionIndex = questionInfo.questionNumber;
    const questionList = questionInfo.questionList || [];
    const count = questionList[questionIndex].questionNumber;
    const typeCode = questionList[questionIndex].typeCode;
    if(typeCode == "RQ22"){
      this.generateCharList();
      this.setData({
        isCircleTopic:true
      })
    } else {
      // 显示左右刻度题，并随机选一个答案方法调用
      if (Math.random() < 0.5) {
        this.getLeftValue();
        this.setData({
          isLeftTopic:true
        })
      } else {
        this.getRightValue();
        this.setData({
          isRightTopic:true
        })
      }
    }
    this.setData({
      totalCount: count,
      questionIndex
    })
  },
  // 设置中间圆形刻度数据
  generateCharList() {
    // 固定顺序的原始数据
    const baseList = [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330];
  
    // 随机选择一个索引作为 "0" 的新位置
    let startIndex;
    do {
      startIndex = Math.floor(Math.random() * baseList.length);
    } while (startIndex === 9); // 排除 index=9 的情况
    // 构建新数组：让 baseList[0] 出现在 newList[startIndex] 的位置
    const newList = new Array(baseList.length);
    for (let i = 0; i < baseList.length; i++) {
      const originalValue = baseList[i]; // 原始值，如 0, 30, ...
      const newIndex = (startIndex + i) % baseList.length; // 新位置
      newList[newIndex] = originalValue;
    }
    // 找出 270° 对应的值（即 newList[9]）
    const answerValue = newList[9]; // 这个值就是答案
    // 从 newList 中随机选出两个不是答案的值
    const candidates = newList.filter(item => item !== answerValue); // 剔除答案
    const selectedValues = [];

    while (selectedValues.length < 2) {
      const value = candidates[Math.floor(Math.random() * candidates.length)];
      if (!selectedValues.includes(value)) {
        selectedValues.push(value);
      }
    }
    // 从 newList 中找出每个值对应的角度（index * 30）
    const charList = selectedValues.map(char => {
      const angleIndex = newList.indexOf(char); // 找到原始角度位置
      return {
        char,
        angle: angleIndex * 30
      };
    });  
    const zoneScale = ( startIndex + 1 ) * 30;
    this.setData({ charList,zoneScale,answerValue });
    this.startCountdown(); // 添加倒计时
    this.setData({
      questionStartTime: new Date().getTime()
    })
  },
  // 左边刻度的高度
  getHeight() {
    const query = this.createSelectorQuery().select('#parentView');
    query.fields({size: true}, (res) => {
      if (res) {
        const parentHeight = res.height; // 获取父元素高度
        const childHeight = parentHeight * 0.11; // 计算 10%
        this.setData({
          childHeight
        });
      }
    }).exec();
  },
  // 设置左边刻度的值
  leftScaleValue() {
    const min = 80;
    const max = 280;
    const count = 8;
    const step = 10; // 步长，控制规律性
    // 找出所有可能作为起始点的值
    const possibleStarts = [];
    for (let i = min; i <= max; i += 10) {
      if (i + step * (count - 1) <= max) {
        possibleStarts.push(i);
      }
    }
    // 随机选择一个起点
    const start = possibleStarts[Math.floor(Math.random() * possibleStarts.length)];
    // 构造等差数列
    let scaleValue = [];
    for (let i = 0; i < count; i++) {
      scaleValue.push(start + i * step);
    }
    // 倒序排列
    scaleValue.sort((a, b) => b - a);
    this.setData({
      scaleValue,
      value:''
    });
  },
  // 获取左边刻度的答案
  getLeftValue() {
    const { scaleValue } = this.data;
    // 获取除了第一个和最后一个以外的所有下标
    const availableIndexes = scaleValue
      .map((_, index) => index)
      .filter(index => index !== 0 && index !== scaleValue.length - 1);
    // 随机选一个
    const randomIndex = availableIndexes[
      Math.floor(Math.random() * availableIndexes.length)
    ];
    const leftValue = scaleValue[randomIndex];
    this.setData({
      leftValue,
      randomIndex,
      questionStartTime: new Date().getTime()
    });
    this.startCountdown(); // 添加倒计时
  },
  // 设置右边刻度的值
  rightScaleValue() {
    const min = 1000;
    const max = 10000;
    const count = 10;
    const step = 100;
    // 找出所有可能作为起始点的值
    const possibleStarts = [];
    for (let i = min; i <= max; i += 100) {
      if (i + step * (count - 1) <= max) {
        possibleStarts.push(i);
      }
    }
    // 随机选择一个起点
    const start = possibleStarts[Math.floor(Math.random() * possibleStarts.length)];
    // 构造等差数列
    let rightList = [];
    for (let i = 0; i < count; i++) {
      rightList.push(start + i * step);
    }
    // 倒序排列
    rightList.sort((a, b) => b - a);
    // 取出第一个和最后一个数
    const firstNumber = rightList[0];
    const lastNumber = rightList[rightList.length - 1];
    // 取出中间部分（去掉首尾）
    const middleArray = rightList.slice(1, -1);
    // 更新 data
    this.setData({
      middleArray,
      firstNumber,
      lastNumber,
      value:''
    });
  },
  // 获取右边刻度的答案
  getRightValue() {
    const { middleArray } = this.data;
    const randomIndex = Math.floor(Math.random() * middleArray.length);
    const rightValue = middleArray[randomIndex];
    this.setData({
      rightValue,
      questionStartTime: new Date().getTime()
    });
    this.startCountdown(); // 添加倒计时
  },
  // 启动倒计时
  startCountdown() {
    const { countdownInterval } = this.data;
    // 清除已有倒计时
    if (countdownInterval) {
      clearInterval(countdownInterval);
    }

    this.setData({ countdownTime: 60 });

    const interval = setInterval(() => {
      this.setData({
        countdownTime: this.data.countdownTime - 1
      });

      if (this.data.countdownTime <= 0) {
        this.handleTimeout(); // 处理超时逻辑
        clearInterval(interval);
      }
    }, 1000);

    this.setData({ countdownInterval: interval });
  },   
  // 超时事件
  handleTimeout() {
    let {isExercise,isCircleTopic} = this.data;
    wx.showToast({
      title: '已超时',
      icon: 'none',
      duration: 1000
    });
    // 添加练习题逻辑
    if (isExercise) {
      setTimeout(() => {
        if(isCircleTopic){
          this.generateCharList();
        } else {
          // 显示左右刻度题，并随机选一个答案方法调用
          if (Math.random() < 0.5) {
            this.setData({
              isLeftTopic:true,
              isRightTopic:false,
              leftValue:0
            })
            this.leftScaleValue();
            this.getLeftValue();
          } else {
            this.setData({
              isRightTopic:true,
              isLeftTopic:false,
              rightValue:0,
            })
            this.rightScaleValue();
            this.getRightValue();
          }
        }
        this.setData({
          tabNum: -1,
          value:''
        })
      }, 1000);
      return;
    }
    // 正式答题超时才记录
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(true);
    this.setData({
      answerRecords: newAnswerRecords
    })
    setTimeout(() => {
      let {count,totalCount} = this.data;
      
      // 无论对错都增加总次数
      let countNum = count + 1;
      if (countNum >= totalCount) {
          //跳转下一题
          let questionNumber = this.data.questionIndex + 1;
          const prevInfo = wx.getStorageSync('questionInfo') || {};
          wx.setStorageSync('questionInfo', {
            ...prevInfo,
            questionNumber
          });
          util.navigateByDesc(questionNumber);
      } else {
        if(isCircleTopic){
          this.generateCharList();
        } else {
          // 显示左右刻度题，并随机选一个答案方法调用
          if (Math.random() < 0.5) {
            this.setData({
              isLeftTopic:true,
              isRightTopic:false,
              leftValue:0
            })
            this.leftScaleValue();
            this.getLeftValue();
          } else {
            this.setData({
              isRightTopic:true,
              isLeftTopic:false,
              rightValue:0,
            })
            this.rightScaleValue();
            this.getRightValue();
          }
        }
      }
      this.setData({
        tabNum: -1,
        count: countNum,
        value:''
      })
    }, 1000);
  },
  //  点击键盘按钮
  onTap(e) {
    const key = e.currentTarget.dataset.value;
    let currentValue = this.data.value;
    if (key === 'delete') {
      this.setData({
        value: currentValue.slice(0, -1)
      })
    } else if (currentValue.length < 4) {
      if (key === 'minus') {
        this.setData({
          value: currentValue + '-'
        })
      } else {
        this.setData({
          value: currentValue + key
        });
      }
    }
    this.setData({
      tabNum: key
    })
  },
  // 提交
  onSubmit() {
    let leftValue = this.data.leftValue.toString();
    let rightValue = this.data.rightValue.toString();
    let answerValue = this.data.answerValue.toString();
    let value = this.data.value.toString();
    let {count,totalCount,isCircleTopic,isLeftTopic,isRightTopic,isExercise} = this.data;
    if (!value) return;

    let isCorrect;
    if(isCircleTopic){
      if (value === answerValue) {
        isCorrect = true
      } else {
        isCorrect = false
      }
    }else if(isLeftTopic){
      if (value === leftValue) {
        isCorrect = true
      } else {
        isCorrect = false
      }
    }else if(isRightTopic){
      if (value === rightValue) {
        isCorrect = true
      } else {
        isCorrect = false
      }
    }

    // 添加练习题逻辑
    if (isExercise) {
      if (isCorrect) {
        // 练习题答对后进入正式答题
        this.setData({
          isExercise: false,
          isShowTip: true,
          count: 0,
          tabNum: -1,
          value: ''
        });
      } else {
        // 练习题答错则提示并重新生成题目
        wx.showToast({
          title: '错误',
          icon: 'none',
          duration: 1000
        });
        
        setTimeout(() => {
          // 重新生成题目
          if(isCircleTopic){
            this.generateCharList();
          } else {
            // 显示左右刻度题，并随机选一个答案方法调用
            if (Math.random() < 0.5) {
              this.setData({
                isLeftTopic:true,
                isRightTopic:false,
                leftValue:0
              })
              this.leftScaleValue();
              this.getLeftValue();
            } else {
              this.setData({
                isRightTopic:true,
                isLeftTopic:false,
                rightValue:0,
              })
              this.rightScaleValue();
              this.getRightValue();
            }
          }
          this.setData({
            tabNum: -1,
            value:''
          })
        }, 1000);
      }
      return;
    }
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, value,isCorrect);
    this.setData({
      answerRecords: newAnswerRecords
    })
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    // 无论对错都增加总次数
    let countNum = count + 1;
    if (countNum >= totalCount) {
        //跳转下一题
        let questionNumber = this.data.questionIndex + 1;
        const prevInfo = wx.getStorageSync('questionInfo') || {};
        wx.setStorageSync('questionInfo', {
          ...prevInfo,
          questionNumber
        });
        util.navigateByDesc(questionNumber);
    } else {
      if(isCircleTopic){
        this.generateCharList();
      } else {
        // 显示左右刻度题，并随机选一个答案方法调用
        if (Math.random() < 0.5) {
          this.setData({
            isLeftTopic:true,
            isRightTopic:false,
            leftValue:0
          })
          this.leftScaleValue();
          this.getLeftValue();
        } else {
          this.setData({
            isRightTopic:true,
            isLeftTopic:false,
            rightValue:0,
          })
          this.rightScaleValue();
          this.getRightValue();
        }
      }
    }
    this.setData({
      tabNum: -1,
      count: countNum,
      value:''
    })
    
  },
  // 开始测试
  onStar() {
    this.setData({
      isShowTip: false,
    })
    if(this.data.isCircleTopic){
      this.generateCharList();
    } else {
      // 显示左右刻度题，并随机选一个答案方法调用
      if (Math.random() < 0.5) {
        this.setData({
          isLeftTopic:true,
          isRightTopic:false,
          leftValue:0
        })
        this.leftScaleValue();
        this.getLeftValue();
      } else {
        this.setData({
          isRightTopic:true,
          isLeftTopic:false,
          rightValue:0,
        })
        this.rightScaleValue();
        this.getRightValue();
      }
    }
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '',isRight = false) {
    const {questionStartTime,questionIndex,isCircleTopic,isLeftTopic,isRightTopic} = this.data;
    const questionList = wx.getStorageSync('questionInfo').questionList;
    const currentTopic = questionList[questionIndex];

    let leftValue = this.data.leftValue.toString();
    let rightValue = this.data.rightValue.toString();
    let answerValue = this.data.answerValue.toString();

    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);

    // 判断是否正确（超时视为错误）
    let option = '';
    if (!isTimeout) {
      option = userOption;
      isRight = isRight ? 1 : 0;
    }

    let rightOption = "";
    if(isCircleTopic){
      rightOption = answerValue
    }else if(isLeftTopic){
      rightOption = leftValue
    }else if(isRightTopic){
      rightOption = rightValue
    }
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: 0,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.typeCode,
      stem: '',
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: rightOption,
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },
  onUnload() {
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
  }
})